import { Component } from "react";

import PropTypes from 'prop-types'

import './tabControl.css'

class TabControl extends Component {
  constructor(props) {
    super(props)

    this.state = {
      currentIndex: 0
    }
  }
  
  render() {
    const { list } = this.props
    const { currentIndex } = this.state
    return (
      <div className="tab">
        {
          list.map((item, index) => {
            return (
              <div
                key={item} 
                className={"tab_item " + (currentIndex === index ? 'active' : '' )}
                onClick={ () => this.itemClick(index) }
              >
                <span>{item}</span>
              </div>
            )
          })
        }
      </div>
    )
  }

  itemClick(index) {
    this.setState({
      currentIndex: index
    })

    //接收父组件的函数 并传当前索引
    const { itemChange } = this.props
    itemChange(index)
  }
}

TabControl.propTypes = {
  list: PropTypes.array.isRequired
}

export default TabControl